package detect;

import interfaces.Detect;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.google.gson.Gson;

import entities.CmsTechnology;
import entities.Domain;

public class DetectCmsvBulletin implements Detect {

	@Override
	public void getInfo(Map<String, Object> obj) {
		Document doc = (Document) obj.get("doc");
		Domain domain = (Domain) obj.get("domain");

		CmsTechnology cmsTechnology = (CmsTechnology) new Gson().fromJson(
				domain.getCmsTechnology(), CmsTechnology.class);

		if (cmsTechnology == null) {
			cmsTechnology = new CmsTechnology();
		}

		try {
			Elements metas = doc.select("head meta");

			String cms_name = "";
			String cms_version = "";

			for (Element meta : metas) {
				String metaname = meta.attr("name");
				String metacontent = meta.attr("content");
				if (metaname.equalsIgnoreCase("generator")
						&& metacontent.toLowerCase().contains("vbulletin")) {
					cms_name = "vBulletin";
					Pattern p = Pattern.compile("([0-9]+[.]{1})+[0-9]{1}");
					Matcher m = p.matcher(metacontent); // get a matcher object
					while (m.find()) {
						cms_version = metacontent.substring(m.start(), m.end());
						break;
					}

					cmsTechnology.setN(cms_name);
					cmsTechnology.setV(cms_version);
				}
			}

			if (!cms_name.isEmpty()) {
				domain.setCmsTechnology(new Gson().toJson(cmsTechnology));
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
